package cn.wolfcode.trip.api.controller;

import cn.wolfcode.trip.core.domain.User;
import cn.wolfcode.trip.core.service.IUserService;
import cn.wolfcode.trip.core.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 会话资源控制器
 */
@RestController
@RequestMapping("sessions")
public class SessionController {

    @Autowired
    private IUserService userService;

    /**
     * 登录接口(会话session)
     * 1.资源路径 /sessions
     * 2.请求动作 post
     * 3.请求参数 邮箱/密码  (用user对象接收)
     * 4.返回结果 JsonResult
     */
    @PostMapping
    public JsonResult login(User user){
        JsonResult json = new JsonResult();
        try {
            User temp = userService.login(user);
            json.setData(temp);//把用户返回给前台
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    /**
     * 注销接口(会话session)
     * 1.资源路径 /sessions
     * 2.请求动作 delete
     * 3.请求参数 无
     * 4.返回结果 JsonResult或者204空文档
     */
    @DeleteMapping
    public void logout(HttpSession session, HttpServletResponse response){
        session.invalidate();
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
